// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import { Loading, Message, MessageBox, elForm } from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import router from './router'
import VueRouter from 'vue-router'
import bus from './components/bus.js'
import axios from 'axios';
import md5 from 'js-md5';
import base64 from 'js-base64';
import { getDateArray } from './assets/js/util';
import store from './assets/js/store';
import Print from './assets/js/print'
import qs from 'qs'
import htmlToPdf from './util/htmlToPdf'
import 'lib-flexible'
import { getMeMsgList } from './url/api';
import './new_property'
import inBody from './components/inBody.vue'
import Hls from 'videojs-contrib-hls'
import "video.js/dist/video-js.css"
import '../static/js/polyfill2';
import '../static/js/jsPlugin-1.2.0.min';
import '../static/js/jquery-1.12.1.min';
import '../static/js/jquery.cookie';
import '../static/js/cryptico.min';
import '../static/js/uuid';
import DHPlayer from '../static/DHPlayer.js'
    
import 'hls.js'

Vue.use(DHPlayer)
Vue.use(htmlToPdf)
Vue.use(Print)
// Vue.$getDateArray = getDateArray
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(Hls);

Vue.prototype.$qs = qs
Vue.use(VueRouter)

Vue.component('inBody',inBody)
Vue.prototype.Bus = bus;
    // 捕捉异常信息
// Vue.config.errorHandler = function(err, vm, info) {
//     // `info` 是 Vue 特定的错误信息，比如错误所在的生命周期钩子
//     // 只在 2.2.0+ 可用
//     let msg = `错误发生在：${info}中，具体信息：${err.stack}`
//         //console.log(msg)
// }
let token;
let dataBase64 = base64.Base64
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

Vue.prototype.debounce = (fn, time) => {
    let timeout = null
    return function () {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            fn.apply(this, arguments)
        }, time);
    }
}
Vue.prototype.throttle = (fn, time) => {
    let flag = true;
    return function () {
        if (!flag) return;
        flag = false;
        fn.apply(this, arguments);
        setTimeout(() => {
            flag = true;
        }, time);
    };
};

router.beforeEach((to, from, next) => {
    // console.log(to)
    let aa = to.meta.id || 1
        // console.log(to)
        // if (to.meta.id) {
        // console.log(sessionStorage.getItem('tenantCode') + ":" + to.meta.id + ":dist")
    token = sessionStorage.getItem('tenantCode') + ":" + aa + ":dist"
        // }
        // console.log(sessionStorage.getItem('token'))
    axios.interceptors.request.use(
        config => {
            if (sessionStorage.getItem('Authorization')) { // 判断是否存在token，如果存在的话，则每个http header都加上token
                config.headers["X-Auth-Token"] = sessionStorage.getItem('Authorization');
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        });
    if (to.path == '/login') {
        sessionStorage.removeItem('Authorization');
    }
    let user = sessionStorage.getItem('Authorization');
//    console.log(user,"AAAAAAAAAAAAAAAA");
    if (!user && to.path != '/login') {
        next({ path: '/login' })
    } else {
        next()
    }
})
window.Vue = new Vue({
        el: '#app',
        router,
        store,
        data: () => {
            return {
                getDateArray: getDateArray,
                uploadToRealPath: '/api/v1.0/upload/uploadfile',
                btnControl: JSON.parse(sessionStorage.getItem('btn')),
            }
        },
        components: { App },
        template: '<App/>'
    })
    // 添加请求拦截器
axios.interceptors.request.use(function(config) {
    // console.log(this.loading)
    // this.loading = true
    let data = ''
    let arrdata = []
        // config.cancelToken = source.token;
    if (token) {
        config.headers.token = dataBase64.encode(token)
        sessionStorage.setItem('token', dataBase64.encode(token))
    }
    // 在发送请求之前做些什么
    return config;
}, function(error) {
    Message.error('网络不给力,请稍后再试!')
        // 对请求错误做些什么
    return Promise.reject(error);
});
let _this = this

// 添加响应拦截器
axios.interceptors.response.use(function(config) {
    // console.log(config.config.url == );
    // console.log(config)
    // 响应成功关闭loading
    if (config.data.code == -1 || config.data.code == 40000 || config.data.code == 40001 || config.data.code == 40002 || config.data.code == 40003 || config.data.code == 40004 || config.data.code == 40005) {
        // MessageBox.alert('登录信息已过期，请重新登录', '提示', {
        //     confirmButtonText: '确定',
        //     callback: action => {
        //         router.push({
        //             path: '/login',
        //             // query: { redirect: router.currentRoute.fullPath } //登录后再跳回此页面时要做的配置
        //         })
        //     }
        // });
        // source.cancel(); // 取消其他正在进行的请求
        router.push({
            path: '/login',
        })
    }
    if (config.data.ok !== true) {

        // console.log("QQQQQQQQQQQQQQQQQ",config);
        // Message.error(config.data.message)

        // config.CancelToken = new cancelToken(() => {})
    }
    // console.log("false",config);

    // this.loading = false
    config.info = config.data;
    return config;
}, function(error) {

    console.log(error.response);
    if(error.response.status == 403 ){
        Message.error({
            message: 'token超时！'
        })
        router.push({
                path: '/login',
                // query: { redirect: router.currentRoute.fullPath } //登录后再跳回此页面时要做的配置
        })
    }
    let message = error.response.data.message;
    Message.error(message && message.length < 20 ? message : '网络不给力,请稍后再试!!!')
        // router.push({
        //         path: '/login',
        //         // query: { redirect: router.currentRoute.fullPath } //登录后再跳回此页面时要做的配置
        // })
        // this.loading = false
        // 对请求错误做些什么
        console.log(error);

    return Promise.reject(error);
});
